<?php
require 'db.php'; // 包含数据库连接
require 'vendor/autoload.php'; // 引入 Composer 自动加载器
include_once 'secret/jwt.php';

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

if (!isset($_COOKIE['token'])) {
    header('Location: index.php');
    exit();
}

$jwt = $_COOKIE['token'];

try {
    $decoded = JWT::decode($jwt, new Key($secretKey, 'HS256'));
    $username = $decoded->data->username;
    $role = $decoded->data->role;
    $user_id = $decoded->data->id;
} catch (Exception $e) {
    echo json_encode([
        'error' => '访问被拒绝: ' . $e->getMessage()
    ]);
    exit();
}

// 获取评论 ID
$commentId = $_POST['comment_id'];

// 检查评论是否存在并由当前用户创建
$stmt = $conn->prepare("SELECT commenter FROM comments WHERE id = ? AND commenter_id = ?");
$stmt->bind_param("ii", $commentId, $user_id);
$stmt->execute();
$stmt->store_result();

if ($stmt->num_rows > 0 || $role==='admin') {
    // 删除评论
    $stmt = $conn->prepare("DELETE FROM comments WHERE id = ?");
    $stmt->bind_param("i", $commentId);
    if ($stmt->execute()) {
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['error' => '删除评论失败']);
    }
} else {
    echo json_encode(['error' => '评论不存在或无权限删除']);
}

?>